﻿using System.Collections.Generic;
using UnityEngine;

public static partial class Extensions
{
    /// <summary>
    /// 仅获取指定子一代物体中的组件
    /// </summary>
    public static T GetComponentInChildren<T>(this Transform transform, string childrenName) where T : Component
    {
        for (int i = 0; i < transform.childCount; i++)
        {
            var child = transform.GetChild(i);
            if (child.name != childrenName)
                continue;
            return child.GetComponent<T>();
        }
        return null;
    }

    /// <summary>
    /// 仅获取子一代物体中的组件
    /// </summary>
    public static T[] GetComponentsInRealChildren<T>(this Transform transform) where T : Component
    {
        var list = new List<T>();
        transform.GetComponentsInChildren(list);
        list.RemoveAll(t => t.transform.parent != transform);
        return list.ToArray();
    }

    /// <summary>
    /// 仅获取子一代物体中的组件
    /// </summary>
    public static void GetComponentsInRealChildren<T>(this Transform transform, List<T> result) where T : Component
    {
        transform.GetComponentsInChildren(result);
        result.RemoveAll(t => t.transform.parent != transform);
    }
}
